﻿using SocketLib;
using System;
using System.Configuration;
using System.ServiceProcess;
using System.Threading;

namespace LeXunTongFace
{
    public partial class ServiceLeXunTong : ServiceBase
    {
        System.Threading.Timer recordTimer;
        UDPserver udp = new UDPserver();
        TCPserver tcp = new TCPserver();
        public ServiceLeXunTong()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            IntialSaveRecord();
            string IP = ConfigurationManager.AppSettings["IP"].ToString();
            int TCPP = Convert.ToInt32(ConfigurationManager.AppSettings["TCPport"].ToString());
            int UDPP = Convert.ToInt32(ConfigurationManager.AppSettings["UDPport"].ToString());

            if (udp.Start(IP, UDPP) && tcp.Start(IP, TCPP)) {
                FileOpetation.SaveRecord(string.Format(@"：{0}：服务启动正常！", DateTime.Now));
            }
            else { 
            this.Stop();
            }
        }

        protected override void OnStop()
        {
            if (recordTimer != null)
            {
                recordTimer.Dispose();
            }
            udp.close();
            tcp.close();
            FileOpetation.SaveRecord(string.Format(@"：{0}：服务停止！", DateTime.Now));
        }
        private void IntialSaveRecord()
        {
            TimerCallback timerCallback = new TimerCallback(CallbackTask);


            AutoResetEvent autoEvent = new AutoResetEvent(false);


            recordTimer = new System.Threading.Timer(timerCallback, autoEvent, 10000, 60000 * 5);
        }


        private void CallbackTask(Object stateInfo)
        {
            int n = Convert.ToInt32(ConfigurationManager.AppSettings["OFFLINE"].ToString());
            dao.SetOffline(n);
        }
    }
}
